/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-03-13 14:28:07
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2023-04-23 10:44:34
 */
import Storage from "./asyncStorage";
import { obj2url } from "./index"

const getBaseUrl = async () => {
    return await Storage.getItem('baseUrl')
}

const getToken = async () => {
    const userdata = await Storage.getItem('user')
    return userdata ? userdata.token : ''
}


export default class Request {

    static async get(url, data, signal) {
        let baseurl = await getBaseUrl()
        let token = await getToken()
        let fulUrl = baseurl + url
        if (data) {
            fulUrl = fulUrl + '?' + obj2url(data)
        }
        let option = {}
        signal ? option.signal = signal : null
        let response = await fetch(fulUrl, {
            ...option,
            method: 'GET',
            headers: { "content-type": "application/json", "Authorization": 'bearer ' + token },
        })
        if (response.status === 401) {
            throw new Error('401')
        }
        let res = await response.json()
        return res
    }

    static async post(url, data, signal) {
        let baseurl = await getBaseUrl()
        let token = await getToken()
        let option = {}
        signal ? option.signal = signal : null
        let response = await fetch(baseurl + url, {
            ...option,
            method: 'POST',
            headers: { "content-type": "application/json", "Authorization": 'bearer ' + token },
            body: data ? JSON.stringify(data) : null
        })
        if (response.status === 401) {
            throw new Error('401')
        }
        let res = await response.json()
        return res
    }
}